package com.bp.hearthealth.pulse.lnapps.bp_network

import com.google.gson.GsonBuilder
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * 网络基础服务配置。
 *
 */
object BpServiceCreator {

    // TODO:  注解中需要配置接口  crash/admin_panel/api.php
    private var BASE_URL = "https://zhaoheyoga.cn/"
    const val API_KEY = "156c4675-9608-4591-1111-00000"
    const val ACCESS_KEY = "05d0a43a34232da067f2db4e7335fe40770edc4a619f7e5eaf9a2ef5d9384a3a"
    const val VIDEO_URL = "http://upload.occuad.net/"

    private val httpClient = OkHttpClient.Builder()
        .callTimeout(20, TimeUnit.SECONDS)
        .connectTimeout(20, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .followRedirects(false)
        .addInterceptor(ChangeBaseUrlInterceptor())
        .addInterceptor(LoggingInterceptor())
        .addInterceptor(HeaderInterceptor())
        .build()

    fun <T> create(clazz: Class<T>): T {
        return getBuilder().create(clazz)
    }

    private fun getBuilder(): Retrofit {
        val builder = Retrofit.Builder()
        if (BpCheckNetwork.isNetworkConnected(BpApplication.context)) {
            builder.client(httpClient)
        }
        builder
            .baseUrl(BASE_URL)
            .client(httpClient)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().registerTypeAdapterFactory(
                        BpGsonTypeAdapterFactory()
                    ).create()
                )
            )
        return builder.build()
    }

    class ChangeBaseUrlInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request: Request = chain.request()
            val oldHttpUrl: HttpUrl = request.url
            val builder: Request.Builder = request.newBuilder()
            if (request.url.toString().contains("api/getUserWithVideoList")) {
                val newBaseUrl = VIDEO_URL.toHttpUrlOrNull()
                val newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl!!.scheme)
                    .host(newBaseUrl.host)
                    .port(newBaseUrl.port)
                    .build()
                return chain.proceed(builder.url(newFullUrl).build())
            }
            return chain.proceed(request)
        }
    }

    private class LoggingInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val response = chain.proceed(chain.request())
            val responseBody = response.body ?: return response
            val mediaType = responseBody.contentType()
            val content = response.body!!.string()
            LogUtil.i("请求数据: ${request.url} \nheader数据：${request.headers}")
            LogUtil.i("响应数据：$content")
            return response.newBuilder().body(ResponseBody.create(mediaType, content)).build()
        }
    }

    class HeaderInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val original = chain.request()
            val request = original.newBuilder().apply {
                header("Api-Key", API_KEY)
                header("Content-Type", "application/json")
                header("charset", "UTF-8")
            }.build()
            return chain.proceed(request)
        }
    }
}

